<?php
App::import('Controller', 'WorkShopApp');
class ServiceAdviserController extends WorkShopAppController
{

    var $uses = array(
        'Customer','CustomerAppointment','CustomerAppointmentParent','ShortMessage','Config'
    );

    # Set the layout to use
    var $layout = 'service_adviser_layout';

    public function beforeFilter($param_array = null)
    {
        parent::beforeFilter(array('user_levels'=>array('Allow All')));
        $this->Auth->allow('cronTask');

    }

    public function index()
    {
        $page_title = 'Dashboard';
        $page_summary = 'Begin Here';
        $page_icon = 'iconfa-laptop';
        $this->set(compact('page_title','page_summary','page_icon'));
    }


    function customers($type = 'get')
    {
        if ($this->request->is('ajax')) {
            $this->autoRender = false;
            $this->autoLayout = false;
            $authUser = $this->Auth->user();
            switch ($type) {
                case 'get' :
                    /**  Get posted data */
                    $page = isset($_POST['page']) ? $_POST['page'] : 1;
                    /** The current page */
                    $sortname = isset($_POST['sortname']) ? $_POST['sortname'] : 'id';
                    /** Sort column */
                    $sortorder = isset($_POST['sortorder']) ? $_POST['sortorder'] : 'desc';
                    /** Sort order */
                    $qtype = isset($_POST['qtype']) ? $_POST['qtype'] : '';
                    /** Search column */
                    $search_query = isset($_POST['query']) ? $_POST['query'] : '';
                    /** Search string */
                    $rp = isset($_POST['rp']) ? $_POST['rp'] : 10;
                    $limit = $rp;
                    $start = ($page - 1) * $rp;

                    $condition_array = array('Customer.type' => 'service_customer','Customer.deleted' => 'n');
                    if (!empty($search_query)) {
                        if ($qtype == 'name' || $qtype == 'address') {
                            $condition_array["Customer.$qtype LIKE"] = $search_query . '%';
                        }
                        else {
                            $condition_array["Customer.$qtype "] = $search_query;
                        }
                    }
                    /*$contain = array(
                        'Region'=>array('fields' => array('Region.id', 'Region.name'))
                    );*/
                    $data_table = $this->Customer->find('all', array('conditions' => $condition_array,'order' => array("Customer.$sortname"=>"$sortorder"), 'limit' => $start . ',' . $limit, 'recursive' => -1));
                    $data_table_count = $this->Customer->find('count', array('conditions' => $condition_array, 'recursive' => -1));

                    $total_records = $data_table_count;

                    if ($data_table) {
                        $return_arr = array();
                        foreach ($data_table as $obj) {
                            $return_arr[] = array(
                                'id' => $obj['Customer']['id'],
                                'cell' => array(
                                    $obj['Customer']['id'],
                                    $obj['Customer']['name'],
                                    $obj['Customer']['telephone'],
                                    $obj['Customer']['email'],
                                    $obj['Customer']['address'],
                                    $obj['Customer']['dob'],
                                    $obj['Customer']['dob_msg']
                                )
                            );
                        }
                        return json_encode(array('success' => true, 'total' => $total_records, 'page' => $page, 'rows' => $return_arr));
                    }
                    else {
                        return json_encode(array('success' => false, 'total' => $total_records, 'page' => $page, 'rows' => array()));
                    }

                    break;

                case 'save' :
                    $data = array('Customer' => $_POST);
                    if($_POST['id'] == 0){
                        $data['Customer']['created_by'] = $authUser['id'];
                        $data['Customer']['type'] = 'service_customer';
                    }
                    else{
                        $data['Customer']['modified_by'] = $authUser['id'];
                    }

                    if ($this->Customer->save($this->sanitize($data))) {
                        if($_POST['id'] > 0){
                            return json_encode(array('code' => 0, 'msg' => 'Data Updated!'));
                        }
                        else{
                            return json_encode(array('code' => 0, 'msg' => 'Data Saved!', 'id'=>$this->Customer->id));
                        }
                    } else {
                        return json_encode(array('code' => 1, 'msg' => 'Some errors occurred.'));
                    }
                    break;

                case 'save_default_birthday_txt':
                    $msg = $this->request->data['Config']['message'];
                    $result = $this->Config->updateAll(
                        array('Config.value' => "'$msg'"),
                        array('Config.key' => 'service_ad_dob_msg')
                    );

                    if ($result) {
                        return json_encode(array('code' => 0, 'msg' => 'Data Saved!'));
                    } else {
                        return json_encode(array('code' => 1, 'msg' => 'Data Save Failed. '));
                    }
                    break;
            }
        }

        $config = $this->Config->getConfigByKey('service_ad_dob_msg');
        $defualt_msg = trim($config['Config']['value']);

        $page_title = 'Manage Customers';
        $page_summary = 'Manage your customers information';
        $page_icon = 'iconfa-group';
        $this->set(compact('page_title','page_summary','page_icon','defualt_msg'));

    }


    function _getFromDate($date, $from){
        //'-1 day,-1 week,-1 month'
        $d_day = date('Y-m-d',(strtotime(date("Y-m-d", strtotime($date)) . $from)));
        return $d_day;
    }

    function schedule_appointments($type = 'get')
    {
        if ($this->request->is('ajax')) {
            $this->autoRender = false;
            $this->autoLayout = false;
            $authUser = $this->Auth->user();
            switch ($type) {
                case 'get' :
                    /**  Get posted data */
                    $page = isset($_POST['page']) ? $_POST['page'] : 1;
                    /** The current page */
                    $sortname = isset($_POST['sortname']) ? $_POST['sortname'] : 'id';
                    /** Sort column */
                    $sortorder = isset($_POST['sortorder']) ? $_POST['sortorder'] : 'desc';
                    /** Sort order */
                    $qtype = isset($_POST['qtype']) ? $_POST['qtype'] : '';
                    /** Search column */
                    $search_query = isset($_POST['query']) ? $_POST['query'] : '';
                    /** Filters **/
                    $filter_customer =   isset($_POST['filter_customer']) ? $_POST['filter_customer'] : '0' ;
                    $filter_reminded =   isset($_POST['filter_reminded']) ? $_POST['filter_reminded'] : '0' ;
                    $filter_serviced =   isset($_POST['filter_serviced']) ? $_POST['filter_serviced'] : '0' ;
                    /** Search string */
                    $rp = isset($_POST['rp']) ? $_POST['rp'] : 10;
                    $limit = $rp;
                    $start = ($page - 1) * $rp;

                    $condition_array = array('CustomerAppointment.deleted' => 'n','Customer.type' => 'service_customer','Customer.deleted' => 'n');
                    if($filter_customer != '0'){
                        $condition_array['CustomerAppointment.customer_id'] = $filter_customer;
                    }
                    if($filter_reminded != '0'){
                        $condition_array['CustomerAppointment.reminded'] = $filter_reminded;
                    }
                    if($filter_serviced != '0'){
                        $condition_array['CustomerAppointment.serviced'] = "$filter_serviced";
                    }

                    if (!empty($search_query)) {
                        if ($qtype == 'name' || $qtype == 'address') {
                            $condition_array["Customer.$qtype LIKE"] = $search_query . '%';
                        }
                        else {
                            $condition_array["Customer.$qtype "] = $search_query;
                        }
                    }
                    //debug($filter_serviced);
                    //debug($condition_array);

                    $contain = array(
                        'Customer'=>array('fields' => array('Customer.id', 'Customer.name'))
                    );
                    $data_table = $this->CustomerAppointment->find('all', array('conditions' => $condition_array,'contain' => $contain ,'order' => array("CustomerAppointment.$sortname"=>"$sortorder"), 'limit' => $start . ',' . $limit, 'recursive' => 1));
                    $data_table_count = $this->CustomerAppointment->find('count', array('conditions' => $condition_array,'recursive' => 1));

                    $total_records = $data_table_count;

                    if ($data_table) {
                        $return_arr = array();
                        foreach ($data_table as $obj) {
                            $return_arr[] = array(
                                'id' => $obj['CustomerAppointment']['id'],
                                'cell' => array(
                                    $obj['CustomerAppointment']['id'],
                                    $obj['Customer']['name'],
                                    $obj['CustomerAppointment']['next_service_date'],
                                    $this->reminder_times[$obj['CustomerAppointment']['reminder_time']],
                                    $obj['CustomerAppointment']['reminded'],
                                    $obj['CustomerAppointment']['serviced']
                                )
                            );
                        }
                        return json_encode(array('success' => true, 'total' => $total_records, 'page' => $page, 'rows' => $return_arr));
                    }
                    else {
                        return json_encode(array('success' => false, 'total' => $total_records, 'page' => $page, 'rows' => array()));
                    }

                    break;

                case 'save' :
                    $data = array('CustomerAppointment' => $_POST);
                    if($_POST['id'] == 0){
                        $data['CustomerAppointment']['created_by'] = $authUser['id'];
                    }
                    else{
                        $data['CustomerAppointment']['modified_by'] = $authUser['id'];
                    }
                    //calculate the reminder date
                    $reminder_date = $this->_getFromDate($data['CustomerAppointment']['next_service_date'],$data['CustomerAppointment']['reminder_time']);
                    $data['CustomerAppointment']['reminder_date'] = $reminder_date;

                    if ($this->CustomerAppointment->save($this->sanitize($data))) {
                        if($_POST['id'] > 0){
                            return json_encode(array('code' => 0, 'msg' => 'Data Updated!'));
                        }
                        else{
                            return json_encode(array('code' => 0, 'msg' => 'Data Saved!', 'id'=>$this->CustomerAppointment->id));
                        }
                    } else {
                        return json_encode(array('code' => 1, 'msg' => 'Some errors occurred.'));
                    }
                    break;

                case 'delete':
                    $ids = $_POST['ids'];
                    $modObj = ClassRegistry::init('CustomerAppointment');
                    $result = $modObj->updateAll(
                        array('CustomerAppointment.deleted' => "'y'",'CustomerAppointment.modified_by' => $authUser['id']),
                        array('CustomerAppointment.id' => $ids)
                    );
                    if ($result) {
                        echo json_encode(array('code' => 0, 'msg' => 'Data Deleted!'));
                    } else {
                        echo json_encode(array('code' => 1, 'msg' => 'Data cannot be deleted'));
                    }
                    break;
            }
        }

        $customers_list = $this->getCustomersList();
        $customers_filter = array(array('value'=>0,'name'=>'All'));
        foreach($customers_list as $k => $v){
            $customers_filter[]= array(
                'value'=>$v['id'],
                'name'=>$v['name'],
            );
        }
        $reminder_time_list = array();
        foreach($this->reminder_times as $k => $v){
            $reminder_time_list[]= array(
                'id'=>$k,
                'name'=>$v,
            );
        }

        $reminded_status_filter = array(array('value'=>0,'name'=>'All'));
        foreach($this->reminded_status as $k => $v){
            $reminded_status_filter[]= array(
                'value'=>$v,
                'name'=>$v,
            );
        }

        $serviced_status_filter = array(array('value'=>0,'name'=>'All'));
        foreach($this->serviced_status as $k => $v){
            $serviced_status_filter[]= array(
                'value'=>$v,
                'name'=>$v,
            );
        }

        $page_title = 'Schedule Appointments';
        $page_summary = 'Manage appointments for your customers';
        $page_icon = 'iconfa-calendar';
        $this->set(compact('page_title','page_summary','page_icon','customers_list','customers_filter','reminder_time_list','serviced_status_filter','reminded_status_filter','customers_filter'));

    }


    function today_reminders()
    {
        if ($this->request->is('ajax')) {
            $this->autoRender = false;
            $this->autoLayout = false;
            $authUser = $this->Auth->user();

        }

        $appointments = $this->CustomerAppointment->getAllAppointments('service_customer');

        $over_due = $this->_get_overdue_appointments('reminders','service_customer');
        $overdue_appointments = $over_due['data'];
        $page_title = 'Today Reminders';
        $page_summary = 'Know who is to be reminded for servicing.';
        $page_icon = 'iconfa-bell';
        $this->set(compact('page_title','page_summary','page_icon','customers_list','reminder_time_list','overdue_appointments','appointments'));

    }


    function today_appointments()
    {
        if ($this->request->is('ajax')) {
            $this->autoRender = false;
            $this->autoLayout = false;
            $authUser = $this->Auth->user();

        }

        $appointments = $this->CustomerAppointment->getAllAppointments('service_customer');
        $today_appointments = $this->_get_today_appointments_count('service_customer');

        $over_due = $this->_get_overdue_appointments('appointments','service_customer');
        $overdue_appointments = $over_due['data'];
        $page_title = 'Today Appointments';
        $page_summary = 'Know who you are expecting for servicing.';
        $page_icon = 'iconfa-wrench';
        $this->set(compact('page_title','page_summary','page_icon','customers_list','reminder_time_list','overdue_appointments','appointments','today_appointments'));

    }


    function service_appointments($type = null)
    {
        if ($this->request->is('ajax')) {
            $this->autoRender = false;
            $this->autoLayout = false;
            $authUser = $this->Auth->user();
            switch ($type) {
                case 'save' :
                    //debug($this->request->data);
                   // exit;
                    $data = $this->request->data;
                    $id = $data['CustomerAppointment']['id'];
                    $edit_instances = $data['CustomerAppointment']['edit_instances'];
                    $parent_id = $data['CustomerAppointmentParent']['id'];
                    $repeat = $data['CustomerAppointmentParent']['repeat'];
                    $prev_repeat_val = $data['CustomerAppointment']['prev_repeat_val'];
                    $repeat_freq = $data['CustomerAppointmentParent']['repeat_freq'];

                    if($id == 0){
                        $data['CustomerAppointment']['created_by'] = $authUser['id'];
                        $data['CustomerAppointmentParent']['created_by'] = $authUser['id'];
                    }
                    else{
                        $data['CustomerAppointment']['modified_by'] = $authUser['id'];
                        $data['CustomerAppointmentParent']['modified_by'] = $authUser['id'];
                    }
                    if(empty($data['CustomerAppointment']['end_date'])){
                        unset($data['CustomerAppointment']['end_date']);
                    }
                    //calculate the reminder date
                    $reminder_date = $this->_getFromDate($data['CustomerAppointment']['next_service_date'],$data['CustomerAppointment']['reminder_time']);
                    //check if reminder date has changed from last update, then set it to 0, if not leave at is.
                    if($id > 0){
                        $r_dt = $this->CustomerAppointment->getReminderById($id);
                        $re_date = $r_dt['CustomerAppointment']['reminder_date'];
                        //$result = $this->CustomerAppointment->compareDate($reminder_date,$re_date);
                        if($re_date != $reminder_date){//reset to zero
                            $data['CustomerAppointment']['reminder_count'] = 0;
                        }
                    }
                    $data['CustomerAppointment']['reminder_date'] = $reminder_date;

                    if ($this->CustomerAppointment->saveAll($this->sanitize($data))) {
                        $save_id = $this->CustomerAppointment->id;
                        $parent_id = $this->CustomerAppointmentParent->id;

                        $params = array(
                            'customer_id'=>$data['CustomerAppointment']['customer_id'],
                            'vehicle_number'=>$data['CustomerAppointment']['vehicle_number'],
                            'vehicle_type'=>$data['CustomerAppointment']['vehicle_type'],
                            'next_service_date'=>$data['CustomerAppointment']['next_service_date'],
                            'reminder_time'=>$data['CustomerAppointment']['reminder_time'],
                            'repeat_freq'=>$repeat_freq,
                            'created_by'=>$authUser['id'],
                            'modified_by'=>$authUser['id']
                        );
                        //Check for recurring events
                        if($id == 0 && $repeat == 'Yes'){//if new event and repeat is on
                            $this->fireRecurringEvents('add',$parent_id,$params);
                        }
                        /*elseif($id > 0 && $repeat == 'Yes' && $edit_instances == 'Yes'){
                            $this->fireRecurringEvents('update',$parent_id,$params);
                        }*/

                        if($id > 0){
                            return json_encode(array('code' => 0, 'msg' => 'Appointment Updated!', 'id'=>$save_id));
                        }
                        else{
                            return json_encode(array('code' => 0, 'msg' => 'Appointment Saved!', 'id'=>$save_id));
                        }
                    } else {
                        return json_encode(array('code' => 1, 'msg' => 'Some errors occurred.'));
                    }
                    break;

                case 'delete':
                    $id = $_POST['id'];
                    $modObj = ClassRegistry::init('CustomerAppointment');
                    $result = $modObj->updateAll(
                        array('CustomerAppointment.deleted' => "'y'",'CustomerAppointment.modified_by' => $authUser['id']),
                        array('CustomerAppointment.id' => $id)
                    );
                    if ($result) {
                        echo json_encode(array('code' => 0, 'msg' => 'Appointment Deleted!'));
                    } else {
                        echo json_encode(array('code' => 1, 'msg' => 'Appointment cannot be deleted'));
                    }
                    break;

                case 'update' ://When an appointment is moved
                    //debug($this->request->data);
                    $id = $_POST['id'];
                    $next_service_date = $_POST['next_service_date'];
                    $reminder_time = $_POST['reminder_time'];
                    $reminder_date = $this->_getFromDate($next_service_date,$reminder_time);
                    $data = array(
                        'id'=>$id,
                        'next_service_date'=>$next_service_date,
                        'reminder_date'=>$reminder_date,
                        'modified_by'=>$authUser['id']
                    );
                    if($id > 0){
                        $r_dt = $this->CustomerAppointment->getReminderById($id);
                        $re_date = $r_dt['CustomerAppointment']['reminder_date'];
                        if($re_date != $reminder_date){//reset to zero
                            //$result = $this->CustomerAppointment->compareDate($re_date,$reminder_date);
                            $data['reminder_count'] = 0;
                        }
                    }

                    if ($this->CustomerAppointment->save($data)) {
                        $save_id = $this->CustomerAppointment->id;
                        if($id > 0){
                            return json_encode(array('code' => 0, 'msg' => 'Appointment Updated!', 'id'=>$save_id));
                        }
                        else{
                            return json_encode(array('code' => 0, 'msg' => 'Appointment Saved!', 'id'=>$save_id));
                        }
                    } else {
                        return json_encode(array('code' => 1, 'msg' => 'Some errors occurred.'));
                    }
                    break;

                case 'turned_up' :
                    //debug($this->request->data);
                    $id = $_POST['id'];
                    $data = array(
                        'id'=>$id,
                        'serviced'=>'Serviced',//Using serviced for turned up
                        'modified_by'=>$authUser['id'],
                        'turned_up_date'=>date('Y-m-d H:i:s')
                    );

                    if ($this->CustomerAppointment->save($data)) {
                        $save_id = $this->CustomerAppointment->id;
                        if($id > 0){
                            return json_encode(array('code' => 0, 'msg' => 'Appointment Updated!', 'id'=>$save_id));
                        }
                        else{
                            return json_encode(array('code' => 0, 'msg' => 'Appointment Saved!', 'id'=>$save_id));
                        }
                    } else {
                        return json_encode(array('code' => 1, 'msg' => 'Some errors occurred.'));
                    }
                    break;

                case 'get_appointments':

                    $start = $_POST['start']=='0' ? null : $_POST['start'];
                    $end = $_POST['end']=='0' ? null : $_POST['end'];
                    $customer = $_POST['customer']=='0' ? null : $_POST['customer'];
                    $vehicle_type = $_POST['vehicle_type']=='0' ? null : $_POST['vehicle_type'];
                    $vehicle_number_P = trim($_POST['vehicle_number']);
                    $vehicle_number = empty($vehicle_number_P) ? null : $vehicle_number_P;

                    $appointments = array();
                    $appointments_data = $this->CustomerAppointment->getAllAppointments('service_customer',$start,$end,$customer,$vehicle_type,$vehicle_number);

                    $lbl = ' Service Appointment';
                    foreach($appointments_data['data'] as $arr){
                        //$title = $arr['name'].' : <strong>'.$lbl."</strong>  <img src='/pos_plant_pool/img/tip.png' width='10' height='10' border='0' />";
                        $title = "<b>".$arr['name']."</b> : ".$lbl." <img src='/jappe/img/tip.png' width='10' height='10' border='0' />";
                        $date = date('Y-m-d',strtotime($arr['next_service_date']));
                        $turned_up = $arr['serviced'];
                        $serviced = $arr['service_status'];
                        $cl = '';
                        $editable = true;
                        if($turned_up == 'Serviced'){
                            $cl = '#333';//default
                            $editable = false;
                        }
                        else{
                            $cl = '#0866c6';//blue
                            if($serviced == 'present'){
                                $cl = '#fcb904';//yellow
                                $editable = false;
                            }
                            else if($serviced == 'past'){
                                $cl = '#dd0000';//red
                                $editable = false;
                            }
                        }
                        $id = $arr['id'];
                        $vehicle_number = $arr['vehicle_number'];
                        $vehicle_type = $arr['vehicle_type'];
                        $next_service_date = $arr['next_service_date'];
                        $end_date = $arr['end_date'];
                        $end_dt_str ='';
                        if(!empty($end_date)){
                            $end_dt_str = $this->convertDate($end_date,'ui');
                        }
                        $reminder_time = $arr['reminder_time'];
                        $reminder_time_name = $this->reminder_times[$reminder_time];
                        $customer_id = $arr['customer_id'];
                        $customer_name = $arr['name'];
                        $repeat = $arr['repeat'];
                        $repeat_freq = $arr['repeat_freq'];
                        $parent_id=$arr['parent_id'];
                        $appointments[]=array(
                            'title'=>$title,
                            'start'=>$date,
                            'color'=>$cl,
                            'editable'=>$editable,
                            'id'=>$id,
                            'end_date'=> empty($end_date)? '' : $end_date,
                            'customer_id'=>$customer_id,
                            'reminder_time'=>$reminder_time,
                            'vehicle_number'=>$vehicle_number,
                            'vehicle_type'=>$vehicle_type,
                            'parent_id'=>$parent_id,
                            'repeat'=>$repeat,
                            'prev_repeat_val'=>$repeat,
                            'repeat_freq'=>$repeat_freq,
                            'btns'=>"<hr style='margin: 8px 0px;' /><button class='btn btn-small edit_app_btn' data-id='$id'> Edit </button> <button class='btn btn-small delete_app_btn' data-id='$id'> Delete </button> <button class='btn btn-small close_app_btn' data-id='$id'> Close </button>",
                            'btns2'=>"<hr style='margin: 8px 0px;' /><button class='btn btn-small close_app_btn' data-id='$id'> Close </button>",
                            //'format_content'=>"<b>When</b>: ".$this->convertDate($next_service_date,'ui')."<br /><b>End</b>: ".$end_dt_str."<br /> <b>Remind Me in</b>: ".$reminder_time_name."<br /> <b>Vehicle Number</b>: ".$vehicle_number."<br /> <b>Vehicle Type</b>: ".$vehicle_type
                            'format_content'=>"<b>When</b>: ".$this->convertDate($next_service_date,'ui')."<br /> <b>Remind Me in</b>: ".$reminder_time_name."<br /> <b>Vehicle Number</b>: ".$vehicle_number."<br /> <b>Vehicle Type</b>: ".$vehicle_type
                        );
                    }

                    if ($appointments) {
                        echo json_encode($appointments);
                    } else {
                        echo json_encode(array());
                    }
                    break;
            }
        }

        $end_date = $this->_getFromDate(date('Y-m-d'),'+1 month');

        $customers_list_d = $this->getCustomersList();
        $customers_list = array();
        $customers_filter_list = array('0'=>'All Customers');
        foreach($customers_list_d as $k => $v){
            $customers_list[$v['id']]= $v['name'];
            $customers_filter_list[$v['id']]= $v['name'];
        }

        $reminder_time_list = array();
        foreach($this->reminder_times as $k => $v){
            $reminder_time_list[$k]= $v;
        }

        $vehicle_type_list = array();
        $vehicle_type_filter_list = array('0'=>'All Vehicle Types');
        foreach($this->vehicle_types as $k => $v){
            $vehicle_type_list[$k]= $v;
            $vehicle_type_filter_list[$k]= $v;
        }

        $cal_repeat_freq = $this->cal_repeat_freq;

        //debug($this->getHolidays());

        $today_appointments = $this->_get_today_appointments_count('service_customer',false);
        $today_reminders = $this->_get_today_reminders_count('service_customer',false);
        $over_due = $this->_get_overdue_appointments('appointments','service_customer');
        $overdue_appointments = $over_due['data'];
        $page_title = 'Service Appointments';
        $page_summary = 'Organise your service appointments';
        $page_icon = 'iconfa-wrench';
        $this->set(compact('page_title','page_summary','page_icon','customers_list','customers_filter_list','reminder_time_list','vehicle_type_list','vehicle_type_filter_list','overdue_appointments','appointments','today_appointments','today_reminders','end_date','cal_repeat_freq'));

    }


    function fireRecurringEvents($type='add',$parent_id=null,$params){

        if($type=='add'){
            $infinity = 365;// 1 yrs
            $save = array();
            $arr = explode('-',$params['repeat_freq']);
            $repeat_freq = $arr[0];
            $start = $params['next_service_date'];
            $until = ($infinity/$repeat_freq);

            for($x = 0; $x <$until; $x++){
                $start_date = strtotime($start . '+' . $repeat_freq . 'DAYS');
                $start = date("Y-m-d", $start_date);
                $reminder_date = $this->_getFromDate($start,$params['reminder_time']);
                $save[]= array(
                    'customer_appointment_parent_id'=>$parent_id,
                    'customer_id'=>$params['customer_id'],
                    'vehicle_number'=>$params['vehicle_number'],
                    'vehicle_type'=>$params['vehicle_type'],
                    'next_service_date'=>$start,
                    'reminder_time'=>$params['reminder_time'],
                    'reminder_date'=>$reminder_date,
                    'created_by'=>$params['created_by']
                );
            }
            $this->CustomerAppointment->saveAll($this->sanitize($save));
        }
        elseif($type=='update'){
            /*$result = $this->CustomerAppointment->updateAll(
                array(
                    'Fee.deleted' => "'y'",
                    'CustomerAppointment.modified_by' => $auth_user['id']
                ),
                array('CustomerAppointment.customer_appointment_parent_id' => $parent_id)
            );*/
        }
        elseif($type=='delete'){
            /*$result = $this->CustomerAppointment->updateAll(
                array(
                    'CustomerAppointment.deleted' => "'y'",
                    'CustomerAppointment.modified_by' => $params['modified_by']
                ),
                array('CustomerAppointment.customer_appointment_parent_id' => $parent_id)
            );*/
        }
    }



    function check_reminders(){
        # disable the rendering of the layout
        $this->autoRender = false;
        $this->autoLayout = false;

        $loggedUser = $this->Auth->user();
        if(!$loggedUser){
            return json_encode(array('code' => 1, 'total_count' => 0));
        }

        if($this->request->is('ajax')){

            $count = $this->_get_today_reminders_count('service_customer');

            $msg_str = "".$count['count']." Customer(s) to be reminded of their vehicle service <br />";

            if ($count > 0) {
                return json_encode(array('code' => 0, 'total_count' => $count['count'], 'data'=>$msg_str));
            }
            else {
                return json_encode(array('code' => 1, 'total_count' => $count['count']));
            }
        }
    }


    function report_appointments(){
        $year = date('Y');
        $month = date('m');
        $day = '';
        $default_month = $month;
        $customer = null;
        if($this->request->is('post')){
            $year = $this->request->data['Query']['year'];
            $month = $this->request->data['Query']['month'];
            $day = trim($this->request->data['Query']['day']);
            //$day = (count($day) > 0 && count($day)==1) ? '0'.$day : $day;
            $customer = $this->request->data['Query']['customer'];
            if($customer == '0'){
                $customer = null;
            }
            $default_month = $month;
        }
        $year_month  = $year.'-'.$month;
        if(!empty($day)){
            $year_month  = $year.'-'.$month.'-'.$day;
        }
        $g_data = $this->CustomerAppointment->reportAppointments($year_month,$customer);
        $count = $g_data['count'];
        $raw_data = $g_data['data'];
        $total_turned_up = isset($raw_data['Serviced'])?  count($raw_data['Serviced']) : 0;
        $total_turned_not_up = isset($raw_data['Not Serviced'])?  count($raw_data['Not Serviced']) : 0;
        $pie_data[] = array(
            'Total Turn Up',
            $total_turned_up
        );
        $pie_data[] = array(
            'Total Non Turn Up',
            $total_turned_not_up
        );

        $customers_list_d = $this->getCustomersList();
        $customers_filter_list = array('0'=>'All Customers');
        foreach($customers_list_d as $k => $v){
            $customers_filter_list[$v['id']]= $v['name'];
        }
        $customer_name = '';
        if($customer != null){
            $customer_name = 'For '.$customers_filter_list[$customer];
        }

        $month_name = $this->getMonths($default_month).' '.$day;

        $graph_title = $month_name.' Service Appointment '.$customer_name;
        $table_title = $month_name.' Service Appointment '.$customer_name;;

        $month_list = $this->getMonths();
        $controller = $this;

        $page_title = 'Monthly Appointments Report';
        $page_summary = 'Get report of customers who turned up and those who did not in every month.';
        $page_icon = 'iconfa-bar-chart';

        $this->set(compact('page_title','page_summary','page_icon','controller','customers_filter_list','table_title','graph_title','raw_data','pie_data','year','month','day','month_list','default_month'));
    }


    function print_export_report_appointments(){
        $media_type = $_POST['data_type'];
        $year = $_POST['data_year'];
        $month = $_POST['data_month'];
        $day = trim($_POST['data_day']);
        $customer = $_POST['data_customer'];
        $status = $_POST['data_status'];
        if($customer == '0'){
            $customer = null;
        }
        $default_month = $month;

        $year_month  = $year.'-'.$month;
        if(!empty($day)){
            $year_month  = $year.'-'.$month.'-'.$day;
        }
        $g_data = $this->CustomerAppointment->reportAppointments($year_month,$customer);
        $count = $g_data['count'];
        $raw_data = $g_data['data'];

        $customers_list_d = $this->getCustomersList();
        foreach($customers_list_d as $k => $v){
            $customers_filter_list[$v['id']]= $v['name'];
        }
        $customer_name = '';
        if($customer != null){
            $customer_name = 'For '.$customers_filter_list[$customer];
        }

        $month_name = $this->getMonths($default_month).' '.$day;

        $graph_title = $month_name.' Service Appointment '.$customer_name;
        $table_title = $month_name.' Service Appointment '.$customer_name;;

        $month_list = $this->getMonths();
        $controller = $this;
        $this->layout = 'print_layout';
        $this->set(compact('controller','customers_filter_list','table_title','graph_title','raw_data','status','media_type','year','month','day','month_list'));
    }


    function sms($type = 'get'){
        if ($this->request->is('ajax')) {
            $this->autoRender = false;
            $this->autoLayout = false;
            $authUser = $this->Auth->user();
            switch ($type) {
                case 'get' :
                    /**  Get posted data */
                    $page = isset($_POST['page']) ? $_POST['page'] : 1;
                    /** The current page */
                    $sortname = isset($_POST['sortname']) ? $_POST['sortname'] : 'id';
                    /** Sort column */
                    $sortorder = isset($_POST['sortorder']) ? $_POST['sortorder'] : 'desc';
                    /** Sort order */
                    $qtype = isset($_POST['qtype']) ? $_POST['qtype'] : '';
                    /** Search column */
                    $search_query = isset($_POST['query']) ? $_POST['query'] : '';
                    /** Search string */
                    $rp = isset($_POST['rp']) ? $_POST['rp'] : 10;
                    $limit = $rp;
                    $start = ($page - 1) * $rp;

                    $condition_array = array('User.user_type' => $authUser['user_type']);
                    if (!empty($search_query)) {
                        if ($qtype == 'name' || $qtype == 'address') {
                            $condition_array["ShortMessage.$qtype LIKE"] = $search_query . '%';
                        }
                        else {
                            $condition_array["ShortMessage.$qtype "] = $search_query;
                        }
                    }
                    $contain = array(
                        'User'=>array('fields' => array('User.id', 'User.user_type','User.fname','User.mname','User.lname'))
                    );
                    $data_table = $this->ShortMessage->find('all', array('conditions' => $condition_array, 'contain' => $contain,'order' => array("ShortMessage.$sortname"=>"$sortorder"), 'limit' => $start . ',' . $limit, 'recursive' => 1));
                    $data_table_count = $this->ShortMessage->find('count', array('conditions' => $condition_array, 'recursive' => 1));

                    $total_records = $data_table_count;

                    if ($data_table) {
                        $return_arr = array();
                        foreach ($data_table as $obj) {
                            $return_arr[] = array(
                                'id' => $obj['ShortMessage']['id'],
                                'cell' => array(
                                    $obj['ShortMessage']['id'],
                                    $obj['User']['fname'].' '.$obj['User']['mname'].' '.$obj['User']['lname'],
                                    $obj['ShortMessage']['fon_number'],
                                    $obj['ShortMessage']['message'],
                                    $obj['ShortMessage']['status'],
                                    $obj['ShortMessage']['created']
                                )
                            );
                        }
                        return json_encode(array('success' => true, 'total' => $total_records, 'page' => $page, 'rows' => $return_arr));
                    }
                    else {
                        return json_encode(array('success' => false, 'total' => $total_records, 'page' => $page, 'rows' => array()));
                    }

                    break;

                case 'send' :
                    $fon_numbers_arr = explode(',',$this->request->data['ShortMessage']['fon_numbers']);
                    $sender = $authUser['id'];
                    $msg = $this->request->data['ShortMessage']['message'];
                    $save = array();
                    foreach($fon_numbers_arr as $fon){
                        $res = $this->Sms->sendSMS($msg, $fon);
                        // $res = "1701|9300499590";
                        $status = $this->sms_status['Failed'];
                        if($res){
                            $explode_arr = explode('|',$res);
                            $status_code = trim($explode_arr[0]);
                            if($status_code == 1701){
                                $status = $this->sms_status['Delivered'];
                            }
                            else{
                                $status = $this->sms_status['Failed'];
                            }
                        }
                        $save[]=array(
                            'user_id'=>$sender,
                            'fon_number'=>$fon,
                            'message'=>$msg,
                            'status'=>$status,
                            'created_by'=>$sender,
                            'modified_by'=>$sender
                        );
                    }

                    if ($this->ShortMessage->saveAll($this->sanitize($save))) {
                        return json_encode(array('code' => 0, 'msg' => 'Message Sent'));
                    } else {
                        return json_encode(array('code' => 1, 'msg' => 'Message Failed '));
                    }
                    break;

                case 're_send':

                    break;
            }
        }

        $controller = $this;

        $page_title = 'Short Messaging System';
        $page_summary = 'Send SMS to any phone number(s)';
        $page_icon = 'iconfa-envelope';

        $this->set(compact('page_title','page_summary','page_icon','controller'));
    }



    //this function will be fire by a scheduler every 5 secs
    function cronTask(){
        $this->autoRender = false;
        $this->autoLayout = false;

        $config = $this->Config->getConfigByKey('service_ad_dob_msg');
        debug($config);

        //$cus = $this->Customer->getBirthdayCustomers('service_customer');
        //debug($cus);
       // $msg = 'Testing Gideon 2 Ways';
        //$res = $this->Sms->sendSMS($msg, 233208373586);
        //$res = $this->Sms->sendSMS($msg, 233266352282);
		//debug($res);
    }

}